package org.btik.video.server.device.udp2;


import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.util.concurrent.ConcurrentLinkedQueue;

public class BufferPool {
    private final Log log = LogFactory.getLog(BufferPool.class);
    /**
     * 接收图片缓冲区大小，<br>
     * 与TCP不同的是，若图片大于当前帧大小,会截断则无法得到完整图片，默认40KB
     */
    private static final int RECEIVE_BUFFER_SIZE = 64512;

    /**
     * 帧缓冲池，避免反复new帧缓冲区
     */
    private final ConcurrentLinkedQueue<FrameBuffer> frameBufferPool = new ConcurrentLinkedQueue<>();

    /**
     * 初始缓存区池大小，本身会自动扩容，随着设备增多可以设置合理值
     */
    private int bufferPoolSize = 500;

    private int maxPoolSize = 8000;

    private final byte[] lock = new byte[0];

    public void setBufferPoolSize(int bufferPoolSize) {
        this.bufferPoolSize = bufferPoolSize;
    }

    public void setMaxPoolSize(int maxPoolSize) {
        this.maxPoolSize = maxPoolSize;
    }

    private void init() {
        for (int i = 0; i < bufferPoolSize; i++) {
            frameBufferPool.add(new FrameBuffer(new byte[RECEIVE_BUFFER_SIZE]));
        }
    }

    public FrameBuffer getFrameBuffer() {
        FrameBuffer buffer = frameBufferPool.poll();
        while (buffer == null) {
            if(bufferPoolSize < maxPoolSize){
                log.info("mem up");
                // 自动扩容
                buffer = new FrameBuffer(new byte[RECEIVE_BUFFER_SIZE]);
            }else {
                synchronized (lock){
                    try {
                        lock.wait(200);
                    } catch (InterruptedException ignored) {

                    }
                }
                frameBufferPool.poll();
            }

        }
        return buffer;
    }

    public void returnBuffer(FrameBuffer buffer) {
        frameBufferPool.add(buffer);

    }

    public BufferPool() {
        init();
    }
}
